﻿using NextEngine.Extens;
using NextEngine.Initial;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NextEngine.HttpEngine
{
    public class HttpConnection
    {
        public async Task<byte[]> RequestAsync(string url, string method, string data, CancellationToken cancellationToken)
        {
            HttpWebRequest httpWebRequest;
            WebResponse response;
            //创建request
            if (method.Equals("POST", StringComparison.CurrentCultureIgnoreCase))
            {
                httpWebRequest = WebRequest.CreateHttp(url);
                httpWebRequest.Method = "POST";
                httpWebRequest.Headers["encryType"] = "3";
                httpWebRequest.Headers["gzipType"] = "0";
                httpWebRequest.Headers["Accept-Encoding"] = "geili-zip";
                httpWebRequest.Headers["Content-Encoding"] = "geili-zip";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                //httpWebRequest.AllowReadStreamBuffering = true;

                using (Stream stream = await httpWebRequest.GetRequestStreamAsync())
                {
                    byte[] content = Encoding.UTF8.GetBytes(data);
                    stream.Write(content, 0, content.Length);
                }
                Task<WebResponse> responseTask = httpWebRequest.GetResponseAsync().WithCancellation<WebResponse>(cancellationToken);
                await responseTask.ConfigureAwait(false);
                response = await responseTask;
            }
            else if ("GET".Equals(method, StringComparison.CurrentCultureIgnoreCase))
            {
                if (!string.IsNullOrEmpty(data))
                {
                    url = string.Concat(url, "?", data);
                }
                httpWebRequest = WebRequest.CreateHttp(url);
                httpWebRequest.Method = "GET";
                response = await httpWebRequest.GetResponseAsync().WithCancellation<WebResponse>(cancellationToken);
            }
            else
            {
                throw new ArgumentException("method can't be null");
            }
            return await PortAdapter.CurrentCompressor.CompressStream(response);
        }
    }
}
